package com.hh.component;

import com.hh.controller.UserController;
import com.hh.mapper.PostMapper;
import com.hh.pojo.Post;
import com.hh.pojo.User;
import com.hh.service.PostService;
import com.hh.service.impl.PostServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/*私密贴 图片拦截器  只有自己可以看到自己的私密图片（防止别人url访问地址栏直接请求别人的私密贴图片）*/
@Component
public class PrivateResourceInterceptor implements HandlerInterceptor {
    @Autowired
    private PostService postService;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    System.out.println("【 ------  into PrivateResourceInterceptor ------- 】");
    // url 访问 http://localhost:8081/static/images/postImage/287-1.jpg
//        System.out.println(request.getQueryString());  // 请求的参数字符串  null
//        System.out.println(request.getRequestURI());  // /static/images/postImage/287-1.jpg
//        System.out.println(request.getRequestURL()); // http://localhost:8081/static/images/postImage/287-1.jpg
//        System.out.println(request.getPathInfo());  // null
//        System.out.println(request.getServletPath()); // /static/images/postImage/287-1.jpg

    String uri = request.getRequestURI(); // 请求的路径（从项目根路径开始）

    // 获取请求的图片名称
    String imgName = uri.substring(uri.lastIndexOf("/") + 1);
    // 因为图片根据 帖子id-序号.类型 命名, 根据图片名称获取到 帖子id
    String postId = imgName.substring(0, imgName.indexOf("-"));

    // 根据id获取帖子、根据request获取当前登录用户
    Post post = postService.getPostInfoById(Integer.parseInt(postId));
    User user = UserController.getCurrentUser(request);

    // 将帖子和 传给 postService 查看用户是否有权限 查看
    if (postService.checkViewAuthority(post, user)){
        return true;
    }else {
        // 没有权限则 重定向到错误页面
        Map<String, String> params = new HashMap<>(); /* 前端errorPage 地址栏添加的参数*/
        params.put("errSection",  URLEncoder.encode("图片","utf8"));  /*无论结果是什么，都属于后台管理模块*/
        params.put("errDesc", URLEncoder.encode("对不起，您暂无权限访问该图片！","utf8"));
        params.put("redctType", "1");  /*1表示 显示返回首页按钮*/

        request.setAttribute("params", params);
        request.getRequestDispatcher("/user/toErrorPage").forward(request, response); // 先请求转发到user控制器
        return false;
    }
}

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 整个请求完成之后，DispatcherServlet也渲染了视图
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
